<!doctype html>
<html class="theme-next use-motion theme-next-mist">
<head>
  
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>

<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

  <meta name="google-site-verification" content="K8DCBviaoTBKVs28YBB7IBIbospQ9RVlgSh81RYMUhY" />


  <meta name="baidu-site-verification" content="tXr3ZTm3Hx" />



  <link rel="stylesheet" type="text/css" href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5"/>


<link rel="stylesheet" type="text/css" href="/css/main.css?v=0.4.5.1"/>

  <meta name="description" content="xgfe's blog. 鲜果前端的技术博客，鲜果前端研发部官方博客。前端基础技术研究：html, html5, javascript, css, css3；前端框架研究：angularJs, react, react native." />


  <meta name="keywords" content="React,国际化," />


  <link rel="alternate" target="_blank" href="/atom.xml" title="xgfe" type="application/atom+xml" />


  <link rel="shorticon icon" type="image/x-icon" href="http://p0.meituan.net/xgfe/2db359f56ce13be30dedef160e0e57ce16958.ico?v=0.4.5.1" />

<meta name="description" content="React 最早由 Facebook 的软件工程师 Jordan Walke 创建，它在 2011 年首次部署在 Facebook 的新闻源中，由于其性能优势明显，很快获得了广泛关注和大规模的使用，如今发展已经非常成熟。基于 React 的渲染原理可以实现很多有意思的功能，例如实现一个 React 的国际化工具。(React v16.3)">
<meta name="keywords" content="React,国际化">
<meta property="og:type" content="article">
<meta property="og:title" content="实现React国际化">
<meta property="og:url" content="http://xgfe.github.io/2018/04/26/jiangxiang/internationalize-your-react-project/index.html">
<meta property="og:site_name" content="xgfe">
<meta property="og:description" content="React 最早由 Facebook 的软件工程师 Jordan Walke 创建，它在 2011 年首次部署在 Facebook 的新闻源中，由于其性能优势明显，很快获得了广泛关注和大规模的使用，如今发展已经非常成熟。基于 React 的渲染原理可以实现很多有意思的功能，例如实现一个 React 的国际化工具。(React v16.3)">
<meta property="og:image" content="http://vfile.meituan.net/xgfe/2f1f2dac01553645441f63da880b712937156.png">
<meta property="og:updated_time" content="2018-05-29T03:15:12.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="实现React国际化">
<meta name="twitter:description" content="React 最早由 Facebook 的软件工程师 Jordan Walke 创建，它在 2011 年首次部署在 Facebook 的新闻源中，由于其性能优势明显，很快获得了广泛关注和大规模的使用，如今发展已经非常成熟。基于 React 的渲染原理可以实现很多有意思的功能，例如实现一个 React 的国际化工具。(React v16.3)">
<meta name="twitter:image" content="http://vfile.meituan.net/xgfe/2f1f2dac01553645441f63da880b712937156.png">


<script type="text/javascript" id="hexo.configuration">
  var CONFIG = {
    scheme: 'Mist',
    sidebar: 'post'
  };
</script>

  <title> 实现React国际化 | xgfe </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
  <div style="position: fixed; top: -9999px; left: -9999px;">
    <img src="http://p0.meituan.net/xgfe/082a9624ba5ae8602150a2d43968463e49348.png" alt="xgfe"/>
  </div>
  <!--[if lte IE 8]>
  <div style=' clear: both; height: 59px; padding:0 0 0 15px; position: relative;margin:0 auto;'>
    <a href="http://windows.microsoft.com/en-US/internet-explorer/products/ie/home?ocid=ie6_countdown_bannercode">
      <img src="http://7u2nvr.com1.z0.glb.clouddn.com/picouterie.jpg" border="0" height="42" width="820"
           alt="You are using an outdated browser. For a faster, safer browsing experience, upgrade for free today or use other browser ,like chrome firefox safari."
           style='margin-left:auto;margin-right:auto;display: block;'/>
    </a>
  </div>
<![endif]-->
  

  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?3601d4483819a5ab6ddabb0b6422a328";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>



  <div class="container one-column page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><h1 class="site-meta">
  <span class="logo-line-before"><i></i></span>
  <a href="/" class="brand" rel="start">
      <span class="logo">
        <i class="icon-next-logo"></i>
      </span>
      <span class="site-title">xgfe</span>
  </a>
  <span class="logo-line-after"><i></i></span>
</h1>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  
  

  
    <ul id="menu" class="menu menu-left">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            <i class="menu-item-icon icon-next-home"></i> <br />
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            <i class="menu-item-icon icon-next-archives"></i> <br />
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            <i class="menu-item-icon icon-next-tags"></i> <br />
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-join">
          <a href="/join" rel="section">
            <i class="menu-item-icon icon-next-join"></i> <br />
            加入我们
          </a>
        </li>
      
      <!-- slide-links added by felix -->
      <li class="menu-item menu-item-slides" style="opacity: 1; transform: translateY(0px);">
        <a href="http://xgfe.github.io/Basics/" target="_blank" rel="section">
          <i class="menu-item-icon icon-next-slides"></i> <br>
          Basics
        </a>
      </li>
      <li class="menu-item menu-item-slides" style="opacity: 1; transform: translateY(0px);">
        <a href="https://slides.com/xgfe" target="_blank" rel="section">
          <i class="menu-item-icon icon-next-slides"></i> <br>
          Slides
        </a>
      </li>

      
      
    </ul>
  

  
    <div class="site-search">
      

    </div>
  

    <div class="site-search">
      <form class="site-search-form" id="gg-form" action="https://www.google.com/webhp" >
        <input type="text" name="q" id="gg-search-input" class="menu-search-input">
      </form>
    </div>
</nav>
 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div id="content" class="content"> 

  <div id="posts" class="posts-expand">
    

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <header class="post-header">

      
      
        <h1 class="post-title" itemprop="name headline">
          
          
            
              实现React国际化
            
          
        </h1>
      

      <div class="post-meta">
        <span class="post-time">
          发表于
          <time itemprop="dateCreated" datetime="2018-04-26T15:00:00+08:00" content="2018-04-26">
            2018-04-26
          </time>
        </span>

        
          <span class="post-category" >
            &nbsp; | &nbsp; 作者
            
              <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                <a href="/categories/jiangxiang/" itemprop="url" rel="index">
                  <span itemprop="name">jiangxiang</span>
                </a>
              </span>

              
              

            
          </span>
        

        
          
        

        <!-- tags 挪动位置 -->
        
          <span class="post-tags">
            &nbsp; | &nbsp;
            
              <a href="/tags/React/" rel="tag"><i class="icon-next-tags"></i>React</a>
            
              <a href="/tags/国际化/" rel="tag"><i class="icon-next-tags"></i>国际化</a>
            
          </span>
        
      </div>
    </header>

    <div class="post-body">

      
      

      
        <span itemprop="articleBody"><p> React 最早由 Facebook 的软件工程师 Jordan Walke 创建，它在 2011 年首次部署在 Facebook 的新闻源中，由于其性能优势明显，很快获得了广泛关注和大规模的使用，如今发展已经非常成熟。<br>基于 React 的渲染原理可以实现很多有意思的功能，例如实现一个 React 的国际化工具。(React v16.3)</p>
<a id="more"></a>
<h2 id="一、现状"><a href="#一、现状" class="headerlink" title="一、现状"></a>一、现状</h2><h3 id="1-1-目前-React-国际化常用的解决方案："><a href="#1-1-目前-React-国际化常用的解决方案：" class="headerlink" title="1.1 目前 React 国际化常用的解决方案："></a>1.1 目前 React 国际化常用的解决方案：</h3><ol>
<li>打包时翻译</li>
<li>动态翻译</li>
<li>生成多个版本</li>
</ol>
<p>比较流行的为 webpack 团队基于打包时翻译的 webpack-i18n-plugin 和 yahoo 团队基于动态翻译的 React-intl</p>
<h3 id="1-2-对比"><a href="#1-2-对比" class="headerlink" title="1.2 对比"></a>1.2 对比</h3><ol>
<li>打包时翻译<br>优点：方案比较成熟，已有成功案例（如很多资讯网站、博客，如 mdn ）<br>缺点：翻译表一旦更新，需要重新打包发布，本地要维护大量的翻译表文件，过于繁琐</li>
<li>动态翻译<br>优点：灵活，翻译表放进 cdn 一句 sql 可以更新，可操作性强<br>缺点：兼容性有待考察，对于不同的项目结构要设置特有的配置</li>
<li>多版本<br>优点：产生的打包文件最小，无需配置<br>缺点：修改过程复杂，应用场景不广泛</li>
</ol>
<h2 id="二、大概的设想"><a href="#二、大概的设想" class="headerlink" title="二、大概的设想"></a>二、大概的设想</h2><h3 id="3-1-翻译语法"><a href="#3-1-翻译语法" class="headerlink" title="3.1 翻译语法"></a>3.1 翻译语法</h3><p>语法分为批量翻译或指定单句不翻译<br>具体通过<code>&lt;Provider/&gt;</code>类以及属性 no-translate 实现<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">// 批量翻译</div><div class="line">&lt;Provider value=&#123;&#123;</div><div class="line">    languageMap, // 语言包</div><div class="line">    language, // 语言类型</div><div class="line">&#125;&#125;&gt;</div><div class="line">    ... (要翻译的代码块)</div><div class="line">&lt;/Provider&gt;</div><div class="line">// 指定不翻译</div><div class="line">&lt;div no-translate&gt;...(不翻译的字符串)&lt;/div&gt;</div></pre></td></tr></table></figure></p>
<h3 id="3-2-方便获取在线的语言包"><a href="#3-2-方便获取在线的语言包" class="headerlink" title="3.2 方便获取在线的语言包"></a>3.2 方便获取在线的语言包</h3><p>可以通过请求获得在线语言包，在下载完成后进行更新</p>
<h2 id="三、核心思路"><a href="#三、核心思路" class="headerlink" title="三、核心思路"></a>三、核心思路</h2><p>实现多语言通俗来说就是：</p>
<ol>
<li>先找到要翻译的文字</li>
<li>请求在线语言包</li>
<li>再对要翻译的文字进行翻译</li>
</ol>
<p>基于以上基本思路再思考，我们都知道， JSX 是 react 的语法糖，而使用高阶函数<code>React.createElement</code>可以重新定义组件的渲染，我们只需要将要翻译的文字在该方法中处理即可。</p>
<p>以下两种写法经 babel 转义，本质上没有区别！</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">class Hello extends React.Component &#123;</div><div class="line">  render() &#123;</div><div class="line">    return React.createElement(&apos;div&apos;, null, `Hello $&#123;this.props.toWhat&#125;`);</div><div class="line">  &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line">ReactDOM.render(</div><div class="line">  React.createElement(Hello, &#123;toWhat: &apos;World&apos;&#125;, null),</div><div class="line">  document.getElementById(&apos;root&apos;)</div><div class="line">);</div></pre></td></tr></table></figure>
<ul>
<li>基于这个想法，通过设置 no-translate 属性，<code>&lt;Provider/&gt;</code>，并在<code>createElement</code>中判断，就知道哪里的文字需要翻译，也知道要翻译成哪种语言了（第一步）！</li>
<li>(第二步比较简单，暂时忽略…)</li>
<li>再定义一个<code>translate</code>函数，接受文字，语言包和翻译表，返回翻译后的文字（第三步）</li>
</ul>
<p>下面的流程图展示了整体的思路：</p>
<p><img src="http://vfile.meituan.net/xgfe/2f1f2dac01553645441f63da880b712937156.png" alt=""></p>
<h2 id="四、实现"><a href="#四、实现" class="headerlink" title="四、实现"></a>四、实现</h2><p>毕竟是要做一个工具库，首先新建一个工程，在 core 文件目录下创建具体文件</p>
<h3 id="4-1-定义一个-languageMap"><a href="#4-1-定义一个-languageMap" class="headerlink" title="4.1 定义一个 languageMap"></a>4.1 定义一个 languageMap</h3><p> languageMap 一定得是单例模式，方便全局调用<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">// file: ./core/languageMap.js</div><div class="line">const translateMap = &#123;&#125;;</div><div class="line">export default translateMap;</div></pre></td></tr></table></figure></p>
<h3 id="4-2-再写一个translate函数"><a href="#4-2-再写一个translate函数" class="headerlink" title="4.2 再写一个translate函数"></a>4.2 再写一个translate函数</h3><p>任何需要翻译的地方，都将会使用这个<code>translate</code>函数，它接受三个参数：</p>
<ul>
<li>content：要翻译的文字</li>
<li>languageMap：语言包</li>
<li>language：语言类型</li>
</ul>
<p>设置 middleware 作为中间件，可以操作翻译前后的字段，可以解决一些兼容性问题，或者实现一些彩蛋的效果…</p>
<p>代码如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div></pre></td><td class="code"><pre><div class="line">// file: ./core/translate.js</div><div class="line">const middleware = &#123;</div><div class="line">  merge: function(obj) &#123;</div><div class="line">    Object.keys(obj).forEach(function(key) &#123;</div><div class="line">      if (key !== &quot;merge&quot;) &#123;</div><div class="line">        middleware[key] = obj[key];</div><div class="line">      &#125;</div><div class="line">    &#125;);</div><div class="line">  &#125;</div><div class="line">&#125;;</div><div class="line"></div><div class="line">const translate = (content, languageMap, language) =&gt; &#123;</div><div class="line">  if (!content) &#123;</div><div class="line">    return &quot;&quot;;</div><div class="line">  &#125;</div><div class="line">  if (!language) &#123;</div><div class="line">    throw new Error(&quot;you should define specific language type!&quot;);</div><div class="line">  &#125;</div><div class="line">  // beforeRender middleware</div><div class="line">  if (middleware.beforeRender) content = middleware.beforeRender(content);</div><div class="line">  // translate words</div><div class="line">  if (language &amp;&amp; languageMap &amp;&amp; languageMap[language]) &#123;</div><div class="line">    languageMap[language][content] &amp;&amp;</div><div class="line">      (content = languageMap[language][content]);</div><div class="line">  &#125;</div><div class="line">  // afterRender middleware</div><div class="line">  if (middleware.afterRender) content = middleware.afterRender(content);</div><div class="line">  return content;</div><div class="line">&#125;;</div></pre></td></tr></table></figure></p>
<h3 id="4-3-再创建-translateClass"><a href="#4-3-再创建-translateClass" class="headerlink" title="4.3 再创建 translateClass"></a>4.3 再创建 translateClass</h3><p>为了使用Context API，我们需要一个辅助类来接受<code>&lt;Provider/&gt;</code>传过来的 languageMap 和 language 等字段</p>
<p>先创建一个./core/context.js<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">export const &#123; Provider, Consumer &#125; = React.createContext();</div></pre></td></tr></table></figure></p>
<p>在创建一个./core/translateClass<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div></pre></td><td class="code"><pre><div class="line">// file: ./core/translateClass.jsx</div><div class="line">import React from &quot;react&quot;;</div><div class="line">import &#123; translate &#125; from &quot;./translate&quot;;</div><div class="line">import &#123; Consumer &#125; from &quot;./context&quot;;</div><div class="line"></div><div class="line">class Translate extends React.Component &#123;</div><div class="line">  render() &#123;</div><div class="line">    const noTranslate = this.props[&quot;no-translate&quot;];</div><div class="line">    return (</div><div class="line">      &lt;Consumer&gt;</div><div class="line">        &#123;context =&gt;</div><div class="line">          noTranslate</div><div class="line">            ? this.props.children</div><div class="line">            : translate(</div><div class="line">                this.props.children,</div><div class="line">                context.languageMap,</div><div class="line">                context.language</div><div class="line">              )</div><div class="line">        &#125;</div><div class="line">      &lt;/Consumer&gt;</div><div class="line">    );</div><div class="line">  &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line">export default Translate;</div></pre></td></tr></table></figure></p>
<h3 id="4-4-改写-createElement"><a href="#4-4-改写-createElement" class="headerlink" title="4.4 改写 createElement"></a>4.4 改写 createElement</h3><p>有了之前的铺垫，可以很快的实现我们自己的<code>createElement</code><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div></pre></td><td class="code"><pre><div class="line">// file: ./core/translateTag.jsx</div><div class="line">import React, &#123; Component &#125; from &quot;react&quot;;</div><div class="line">import Translate from &quot;./translateClass&quot;;</div><div class="line"></div><div class="line">const createElement = React.createElement;</div><div class="line"></div><div class="line">React.createElement = (...args) =&gt; &#123;</div><div class="line">  let children = args.slice(2);</div><div class="line"></div><div class="line">  // ① console.log(args)</div><div class="line">  children = children.map(child =&gt; &#123;</div><div class="line">    if (typeof args[0] === &quot;string&quot; &amp;&amp; typeof child === &quot;string&quot;) &#123;</div><div class="line">      if (args[1] &amp;&amp; args[1][&quot;no-translate&quot;]) &#123;</div><div class="line">        return &lt;Translate no-translate&gt;&#123;child&#125;&lt;/Translate&gt;;</div><div class="line">      &#125; else &#123;</div><div class="line">        return &lt;Translate&gt;&#123;child&#125;&lt;/Translate&gt;;</div><div class="line">      &#125;</div><div class="line">    &#125;</div><div class="line">    return child;</div><div class="line">  &#125;);</div><div class="line"></div><div class="line">  return createElement(args[0], args[1], ...children);</div><div class="line">&#125;;</div></pre></td></tr></table></figure></p>
<p>在标志①处打印 args 可以看到 ReactDom 的结构，它包含了$$typeof,props,ref,children等属性， $$typeof 代表组件类型， props 是属性， children 是子节点的若干元素，将其 children 获取到，进行如下判断：</p>
<ol>
<li>如果类型是 Object 就不做任何操作</li>
<li>如果 child 类型是字符串就进行翻译</li>
<li>如带有 no-translate 属性将不对其进行翻译</li>
</ol>
<p>通过改变<code>&lt;Provider/&gt;</code>的位置，可以设置不同区块的 context ，这样可以改变不同区块的翻译表和语言类型</p>
<p>到这里， translate 工具类基本完成</p>
<h2 id="五、进行测试"><a href="#五、进行测试" class="headerlink" title="五、进行测试"></a>五、进行测试</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div></pre></td><td class="code"><pre><div class="line">import React, &#123; Component &#125; from &quot;react&quot;;</div><div class="line">import ReactDom from &quot;react-dom&quot;;</div><div class="line">import languageMap from &quot;./core/languageMap&quot;;</div><div class="line">import &#123; translate, middleware &#125; from &quot;./core/translate&quot;;</div><div class="line">import &#123; Provider &#125; from &quot;./core/context&quot;;</div><div class="line">// 全局更新createElement</div><div class="line">import &quot;./core/translateTag.jsx&quot;;</div><div class="line"></div><div class="line">const styles = &#123;</div><div class="line">  fontFamily: &quot;sans-serif&quot;,</div><div class="line">  textAlign: &quot;center&quot;</div><div class="line">&#125;;</div><div class="line"></div><div class="line">class App extends Component &#123;</div><div class="line">  constructor(...args) &#123;</div><div class="line">    super(...args);</div><div class="line">  &#125;</div><div class="line"></div><div class="line">  componentWillMount() &#123;</div><div class="line">    this.fetchTranslateList();</div><div class="line">  &#125;</div><div class="line"></div><div class="line">  fetchTranslateList() &#123;</div><div class="line">    languageMap[&quot;en&quot;] = &#123;</div><div class="line">      你好: &quot;Hello&quot;,</div><div class="line">      国际化: &quot;intl&quot;</div><div class="line">    &#125;;</div><div class="line">    languageMap[&quot;france&quot;] = &#123;</div><div class="line">      你好: &quot;Bonjour&quot;,</div><div class="line">      国际化: &quot;intl&quot;</div><div class="line">    &#125;;</div><div class="line">  &#125;</div><div class="line"></div><div class="line">  render() &#123;</div><div class="line">    const enConfig = &#123; language: &quot;en&quot;, languageMap &#125;;</div><div class="line">    const franceConfig = &#123; language: &quot;france&quot;, languageMap &#125;;</div><div class="line">    return (</div><div class="line">      &lt;div style=&#123;styles&#125;&gt;</div><div class="line">        &lt;Provider value=&#123;enConfig&#125;&gt;</div><div class="line">          &lt;div&gt;</div><div class="line">            &lt;h1&gt;你好&lt;/h1&gt;</div><div class="line">            &lt;span&gt;</div><div class="line">              你好</div><div class="line">              &lt;Provider value=&#123;franceConfig&#125;&gt;</div><div class="line">                &lt;h1 no-translate&gt;</div><div class="line">                  你好</div><div class="line">                  &lt;div&gt;国际化&lt;/div&gt;</div><div class="line">                &lt;/h1&gt;</div><div class="line">                &lt;span&gt;国际化&lt;/span&gt;</div><div class="line">              &lt;/Provider&gt;</div><div class="line">            &lt;/span&gt;</div><div class="line">          &lt;/div&gt;</div><div class="line">        &lt;/Provider&gt;</div><div class="line">      &lt;/div&gt;</div><div class="line">    );</div><div class="line">  &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line">ReactDom.render(</div><div class="line">  &lt;App /&gt;,</div><div class="line">  document.body.appendChild(document.createElement(&quot;div&quot;))</div><div class="line">);</div></pre></td></tr></table></figure>
<p>以上代码，我们创建了一个入口文件，分别将中文翻译成了英文和法文，最终运行正常！</p>
<h2 id="六、兼容性"><a href="#六、兼容性" class="headerlink" title="六、兼容性"></a>六、兼容性</h2><p>写这个工具的初衷当然是无缝兼容各种 react 项目，但事实上并不简单<br>举例来说，目前出现的很多的前端组件库与这个工具有很多兼容性冲突，这些库主要有：</p>
<ol>
<li>ant-design/ant-mobile（蚂蚁金服团队的前端UI组件库，链接：<a href="https://ant.design/index-cn）" target="_blank" rel="external">https://ant.design/index-cn）</a></li>
<li>element-react（饿了么团队的前端UI组件库react版本，链接：<a href="https://eleme.github.io/element-react/）" target="_blank" rel="external">https://eleme.github.io/element-react/）</a></li>
</ol>
<p>实际操作中发现了不兼容的问题很多，想必要做到开箱即用是不可能了~~~<br>寄希望于无缝兼容，不如提供中间件接口来让使用者自行配置 o(╥﹏╥)o</p>
<h3 id="6-1-ant-design"><a href="#6-1-ant-design" class="headerlink" title="6.1 ant-design"></a>6.1 ant-design</h3><p>例如，在 ant-design 组件库中，<code>&lt;input/&gt;</code>的 placeholder 属性，如不进行检测，将不会被翻译</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div></pre></td><td class="code"><pre><div class="line">import &#123;filter&#125; from &apos;./core/translate.js&apos;;</div><div class="line"></div><div class="line">filter.forAntDesign = (props,language) =&gt; &#123;</div><div class="line">    let props = Object.assign(&#123;&#125;, props);</div><div class="line">            if (language &amp;&amp; props.placeholder) &#123;</div><div class="line">                if (languageMap[language]) &#123;</div><div class="line">                    if (/[^\u4e00-\u9fa5]/g.test(props.placeholder)) &#123;</div><div class="line">                        props.placeholder = props.placeholder.replace(/([\u4e00-\u9fa5]+)/g, (match) =&gt; &#123;</div><div class="line">                            return languageMap[language][match] ? languageMap[language][match] : match</div><div class="line">                        &#125;)</div><div class="line">                    &#125; else &#123;</div><div class="line">                        languageMap[language][props.placeholder] &amp;&amp; (props.placeholder = languageMap[language][props.placeholder]);</div><div class="line">                    &#125;</div><div class="line">                &#125;</div><div class="line">            &#125;</div><div class="line">            return &lt;input</div><div class="line">                &#123;...props&#125;</div><div class="line">                ref=&quot;input&quot;</div><div class="line">                onInput=&#123;e =&gt; &#123;this.value = e.target.value; this.props.onInput &amp;&amp; this.props.onInput(e);&#125;&#125;&gt;</div><div class="line">                &#123;this.props.children&#125;</div><div class="line">            &lt;/input&gt;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>通过如上对 placeholder 的过滤操作，可以实现 ant-design 输入框的多语言翻译。<br>再如，<code>&lt;Select/&gt;</code>组件，它约定元素 option 的属性 value 强等于内容 children 时才认为当前选项是被选中，解决办法这里不再赘述，它们都可以通过增加中间件，修改<code>props.children</code>的过滤机制进而解决！</p>
<h3 id="6-2-其他react组件库"><a href="#6-2-其他react组件库" class="headerlink" title="6.2 其他react组件库"></a>6.2 其他react组件库</h3><p>也有一些框架或者自行编写的组件，如 element-react ，一些 dom 文字并不会放在 text 中，更确切地说其组件内部进行了重构，并不会将文字简单的向外展示，这就需要额外的编写特殊的 filter 了</p>
<h2 id="七、总结"><a href="#七、总结" class="headerlink" title="七、总结"></a>七、总结</h2><p>到这里，我们的 React 国际化工具已经实现了，这里是一个简单的在线 demo</p>
<iframe src="https://codesandbox.io/embed/64zx97v9qr" style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;" sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe>

<ul>
<li>完整代码参考 github: <a href="https://github.com/ranrantu/react-i18" target="_blank" rel="external">https://github.com/ranrantu/react-i18</a></li>
</ul>
<p>总之，这可以说是 React 动态翻译的一种思路，这种实现至今还是有不足的地方，还请各位拍砖指正，感谢！</p>
</span>
      
    </div>

    <footer class="post-footer">

      
        <div class="post-nav">
          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/04/26/wangpeng/lottie_android/" rel="prev">动画库 Lottie 的使用</a>
            
          </div>

          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/04/15/zhangjianfeng/web前端性能优化/" rel="next">web前端性能优化</a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
  <a class="jiathis_button_tsina"></a>
  <a class="jiathis_button_tqq"></a>
  <a class="jiathis_button_weixin"></a>
  <a class="jiathis_button_cqq"></a>
  <a class="jiathis_button_douban"></a>
  <a class="jiathis_button_renren"></a>
  <a class="jiathis_button_qzone"></a>
  <a class="jiathis_button_kaixin001"></a>
  <a class="jiathis_button_copy"></a>
  <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank"></a>
  <a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
  var jiathis_config={
    hideMore:false
  }
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js" charset="utf-8"></script>
<!-- JiaThis Button END -->

      
    </div>
  </div>

 </div>

        

        
          <div class="comments" id="comments">
            <div id="SOHUCS" sid="" ></div>
          </div>
        
      </div>

      
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <a href="https://github.com/xgfe" target="_blank"><img class="site-author-image" src="http://p0.meituan.net/xgfe/082a9624ba5ae8602150a2d43968463e49348.png" alt="xgfe" itemprop="image"/></a>
          <p class="site-author-name" itemprop="name">xgfe</p>
        </div>
        <p class="site-description motion-element" itemprop="description">xgfe's blog. 鲜果前端的技术博客，鲜果前端研发部官方博客。前端基础技术研究：html, html5, javascript, css, css3；前端框架研究：angularJs, react, react native.</p>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">89</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          <div class="site-state-item site-state-categories">
            
              <span class="site-state-item-count">37</span>
              <span class="site-state-item-name">作者</span>
              
          </div>

          <div class="site-state-item site-state-tags">
            <a href="/tags">
              <span class="site-state-item-count">131</span>
              <span class="site-state-item-name">标签</span>
              </a>
          </div>

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" target="_blank" rel="alternate">
              <i class="menu-item-icon icon-next-feed"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/xgfe" target="_blank">GitHub</a>
              </span>
            
          
        </div>

        
        

        <div class="links-of-author motion-element">
          
        </div>

      </section>

      
        <section class="post-toc-wrap sidebar-panel-active">
          <div class="post-toc-indicator-top post-toc-indicator"></div>
          <div class="post-toc">
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#一、现状"><span class="nav-number">1.</span> <span class="nav-text">一、现状</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-目前-React-国际化常用的解决方案："><span class="nav-number">1.1.</span> <span class="nav-text">1.1 目前 React 国际化常用的解决方案：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2-对比"><span class="nav-number">1.2.</span> <span class="nav-text">1.2 对比</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二、大概的设想"><span class="nav-number">2.</span> <span class="nav-text">二、大概的设想</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-翻译语法"><span class="nav-number">2.1.</span> <span class="nav-text">3.1 翻译语法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-方便获取在线的语言包"><span class="nav-number">2.2.</span> <span class="nav-text">3.2 方便获取在线的语言包</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#三、核心思路"><span class="nav-number">3.</span> <span class="nav-text">三、核心思路</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#四、实现"><span class="nav-number">4.</span> <span class="nav-text">四、实现</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-1-定义一个-languageMap"><span class="nav-number">4.1.</span> <span class="nav-text">4.1 定义一个 languageMap</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-2-再写一个translate函数"><span class="nav-number">4.2.</span> <span class="nav-text">4.2 再写一个translate函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-3-再创建-translateClass"><span class="nav-number">4.3.</span> <span class="nav-text">4.3 再创建 translateClass</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-4-改写-createElement"><span class="nav-number">4.4.</span> <span class="nav-text">4.4 改写 createElement</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#五、进行测试"><span class="nav-number">5.</span> <span class="nav-text">五、进行测试</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#六、兼容性"><span class="nav-number">6.</span> <span class="nav-text">六、兼容性</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#6-1-ant-design"><span class="nav-number">6.1.</span> <span class="nav-text">6.1 ant-design</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-2-其他react组件库"><span class="nav-number">6.2.</span> <span class="nav-text">6.2 其他react组件库</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#七、总结"><span class="nav-number">7.</span> <span class="nav-text">七、总结</span></a></li></ol></div>
            
          </div>
          <div class="post-toc-indicator-bottom post-toc-indicator"></div>
        </section>
      

    </div>
  </aside>


    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner"> <div class="copyright" >
  
  &copy; &nbsp; 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="icon-next-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xgfe</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" target="_blank" href="http://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


 </div>
    </footer>

    <div class="back-to-top"></div>
  </div>

  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  
  
    <script type="text/javascript"> 
(function(){ 
var appid = 'cysWiXvkm'; 
var conf = 'prod_fc970dbe85103c7a79b2c4f3dc7fb190'; 
var width = window.innerWidth || document.documentElement.clientWidth; 
if (width < 960) { 
window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="http://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("http://changyan.sohu.com/upload/changyan.js",function(){window.changyan.api.config({appid:appid,conf:conf})}); } })(); </script>
    

  


  
  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js"></script>
  <script type="text/javascript" src="/js/fancy-box.js?v=0.4.5.1"></script>


  <script type="text/javascript" src="/js/helpers.js?v=0.4.5.1"></script>
  

  <script type="text/javascript" src="/vendors/velocity/velocity.min.js"></script>
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js"></script>

  <script type="text/javascript" src="/js/motion_global.js?v=0.4.5.1" id="motion.global"></script>




  <script type="text/javascript" src="/js/nav-toggle.js?v=0.4.5.1"></script>
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  
<script type="text/javascript" src="/js/bootstrap.scrollspy.js?v=0.4.5.1" id="bootstrap.scrollspy.custom"></script>


<script type="text/javascript" id="sidebar.toc.highlight">
  $(document).ready(function () {
    var tocSelector = '.post-toc';
    var $tocSelector = $(tocSelector);
    var activeCurrentSelector = '.active-current';

    $tocSelector
      .on('activate.bs.scrollspy', function () {
        var $currentActiveElement = $(tocSelector + ' .active').last();

        removeCurrentActiveClass();
        $currentActiveElement.addClass('active-current');

        $tocSelector[0].scrollTop = $currentActiveElement.position().top;
      })
      .on('clear.bs.scrollspy', function () {
        removeCurrentActiveClass();
      });

    function removeCurrentActiveClass () {
      $(tocSelector + ' ' + activeCurrentSelector)
        .removeClass(activeCurrentSelector.substring(1));
    }

    function processTOC () {
      getTOCMaxHeight();
      toggleTOCOverflowIndicators();
    }

    function getTOCMaxHeight () {
      var height = $('.sidebar').height() -
                   $tocSelector.position().top -
                   $('.post-toc-indicator-bottom').height();

      $tocSelector.css('height', height);

      return height;
    }

    function toggleTOCOverflowIndicators () {
      tocOverflowIndicator(
        '.post-toc-indicator-top',
        $tocSelector.scrollTop() > 0 ? 'show' : 'hide'
      );

      tocOverflowIndicator(
        '.post-toc-indicator-bottom',
        $tocSelector.scrollTop() >= $tocSelector.find('ol').height() - $tocSelector.height() ? 'hide' : 'show'
      )
    }

    $(document).on('sidebar.motion.complete', function () {
      processTOC();
    });

    $('body').scrollspy({ target: tocSelector });
    $(window).on('resize', function () {
      if ( $('.sidebar').hasClass('sidebar-active') ) {
        processTOC();
      }
    });

    onScroll($tocSelector);

    function onScroll (element) {
      element.on('mousewheel DOMMouseScroll', function (event) {
          var oe = event.originalEvent;
          var delta = oe.wheelDelta || -oe.detail;

          this.scrollTop += ( delta < 0 ? 1 : -1 ) * 30;
          event.preventDefault();

          toggleTOCOverflowIndicators();
      });
    }

    function tocOverflowIndicator (indicator, action) {
      var $indicator = $(indicator);
      var opacity = action === 'show' ? 0.4 : 0;
      $indicator.velocity ?
        $indicator.velocity('stop').velocity({
          opacity: opacity
        }, { duration: 100 }) :
        $indicator.stop().animate({
          opacity: opacity
        }, 100);
    }

  });
</script>

<script type="text/javascript" id="sidebar.nav">
  $(document).ready(function () {
    var html = $('html');
    var TAB_ANIMATE_DURATION = 200;
    var hasVelocity = $.isFunction(html.velocity);

    $('.sidebar-nav li').on('click', function () {
      var item = $(this);
      var activeTabClassName = 'sidebar-nav-active';
      var activePanelClassName = 'sidebar-panel-active';
      if (item.hasClass(activeTabClassName)) {
        return;
      }

      var currentTarget = $('.' + activePanelClassName);
      var target = $('.' + item.data('target'));

      hasVelocity ?
        currentTarget.velocity('transition.slideUpOut', TAB_ANIMATE_DURATION, function () {
          target
            .velocity('stop')
            .velocity('transition.slideDownIn', TAB_ANIMATE_DURATION)
            .addClass(activePanelClassName);
        }) :
        currentTarget.animate({ opacity: 0 }, TAB_ANIMATE_DURATION, function () {
          currentTarget.hide();
          target
            .stop()
            .css({'opacity': 0, 'display': 'block'})
            .animate({ opacity: 1 }, TAB_ANIMATE_DURATION, function () {
              currentTarget.removeClass(activePanelClassName);
              target.addClass(activePanelClassName);
            });
        });

      item.siblings().removeClass(activeTabClassName);
      item.addClass(activeTabClassName);
    });

    $('.post-toc a').on('click', function (e) {
      e.preventDefault();
      var targetSelector = escapeSelector(this.getAttribute('href'));
      var offset = $(targetSelector).offset().top;
      hasVelocity ?
        html.velocity('stop').velocity('scroll', {
          offset: offset  + 'px',
          mobileHA: false
        }) :
        $('html, body').stop().animate({
          scrollTop: offset
        }, 500);
    });

    // Expand sidebar on post detail page by default, when post has a toc.
    var $tocContent = $('.post-toc-content');
    if (isDesktop() && CONFIG.sidebar === 'post') {
      if ($tocContent.length > 0 && $tocContent.html().trim().length > 0) {
        displaySidebar();
      }
    }
  });
</script>



  <script type="text/javascript">
    $(document).ready(function () {
      if (CONFIG.sidebar === 'always') {
        displaySidebar();
      }
      if (isMobile()) {
        FastClick.attach(document.body);
      }
    });
  </script>

  

  
  

  
  <script type="text/javascript" src="/js/lazyload.js"></script>
  <script type="text/javascript">
    $(function () {
      $("#posts").find('img').lazyload({
        placeholder: "/images/loading.gif",
        effect: "fadeIn"
      });
    });
  </script>

  <!-- google search, added by felix -->
  <script>
      $('#gg-form').on('submit', function(e) {
        var keyword = $.trim($(this).find('#gg-search-input').val());
        if (keyword) {
          location.href = 'https://www.google.com.hk/?gfe_rd=cr&ei=hXw8VpjtHuLC8AeSuIjQAg&gws_rd=ssl#safe=strict&q='+encodeURIComponent(keyword)+'+site:xgfe.github.io';
        }
        return false;
      });
  </script>
  <!-- baidu 站长自动推送 -->
  <script>
  (function(){
      var bp = document.createElement('script');
      bp.src = '//push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
  })();
  </script>
</body>
</html>
